package com;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class WebSaver {


    public static void main(String[] args) {

        for(String arg : args){

            try {
                URL url = new URL(arg);
                saveFile(url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    public static void saveFile(URL url) throws IOException {

        URLConnection urlConnection = url.openConnection();

        int contentLength = urlConnection.getContentLength();

        if(contentLength == -1){

            System.out.println("未指定长度");

            return;

        }

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        int offset = 0;

        byte[] bytes = new byte[contentLength];

        while (offset < contentLength){

            int read = in.read(bytes,offset,bytes.length-offset);

            if(read == -1)
                break;

            offset += read;

        }

        in.close();

        if(offset != contentLength){

            throw new IOException("未传输完全");

        }

        String fileName = url.getFile();

        //System.out.println(fileName);

        fileName = fileName.substring(fileName.lastIndexOf('/')+1);

        try (OutputStream out = new FileOutputStream(fileName)){
            out.write(bytes);
            out.flush();
        }
    }

}
